<template>
  <div>
    <el-form :disabled="readonly">
      <div
        v-for="(port, idx) in container.ports ?? []"
        :key="idx"
        class="port-edit-row"
      >
        <el-select v-model="port.protocol">
          <template #prefix>
            <span>协议</span>
          </template>
          <el-option
            v-for="item in uiState.protocol_list"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input v-model="port.name">
          <template #prefix>
            <span>名称</span>
          </template>
        </el-input>
        <el-input v-model="port.containerPort">
          <template #prefix>
            <span>容器端口</span>
          </template>
        </el-input>
        <el-button
          icon="Delete"
          circle
          size="small"
          @click="onDeletePort(idx)"
        />
      </div>
      <div class="w-full flex justify-end">
        <el-button icon="Plus" type="primary" size="small" @click="onAddPort">
          添加端口
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { Container } from "../../../api/k8s";

type Prop = {
  readonly?: boolean;
};
const props = withDefaults(defineProps<Prop>(), {
  readonly: false
});

const container = defineModel<Container>("container");

const uiState = reactive({
  protocol_list: [
    { label: "TCP", value: "TCP" },
    { label: "UDP", value: "UDP" }
  ]
});

const onDeletePort = (index: number) => {
  container.value.ports?.splice(index, 1);
};

const onAddPort = () => {
  if (!container.value.ports) {
    container.value.ports = [];
  }
  container.value.ports.push({
    name: "",
    protocol: "TCP"
  });
};
</script>
<style scoped lang="scss">
.port-edit-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  border: var(--el-border);
  padding: 5px;
  background-color: var(--el-border-color);
}
</style>
